package wangjg.xuexiban.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import wangjg.xuexiban.vo.Bundle;
import android.net.http.AndroidHttpClient;
import android.os.StrictMode;
import android.util.Log;

public class WebClient {
	private String dataRoot;
	
	public WebClient(String dataRoot) {
		this.dataRoot = dataRoot;
	}

	public void login(){
		
	}
	
	public static interface Callback{
		public void handle(String filePath);
	}
	
	public void download(final String url, final Callback callback) {
		new Thread(){
			public void run(){
				String filePath = _download(url, dataRoot);
				callback.handle(filePath);
			}
		}.start();
	}
	
	public List<Bundle> loadList() throws JSONException{
		List<Bundle> list = new ArrayList<Bundle>();
		String json = this.loadText("http://192.168.1.28/cardlist.txt", "utf-8");
		JSONTokener tokener = new JSONTokener(json);
		JSONObject jsonObject = null;
		while((jsonObject = (JSONObject)tokener.nextValue())!=JSONObject.NULL){
			Bundle bundle = new Bundle();
			bundle.setId(jsonObject.getString("id"));
			bundle.setName(jsonObject.getString("name"));
			bundle.setPic(jsonObject.getString("pic"));
			bundle.setFile(jsonObject.getString("file"));
			list.add(bundle);
		}
		return list;
	}
	
	public String _download(String url, String savedDir) {
		AndroidHttpClient client = null;
		try {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().build());
			client = AndroidHttpClient.newInstance("xuexiban");
			// 创建 HttpGet 方法，该方法会自动处理 URL 地址的重定向
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = client.execute(httpGet);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				// 错误处理
				return null;
			}
			HttpEntity entity = response.getEntity();
			String fileName = this.getFileName(response, httpGet);
			InputStream is = entity.getContent();
			String filePath = savedDir + fileName;
			OutputStream os = new FileOutputStream(filePath);
			this.copyAndClose(is, os);
			return filePath;
		} catch (Exception e) {
			Log.e(this.getClass().getSimpleName(), "下载错误", e);
		}finally{
			if(client!=null)
				client.close();
		}
		return null;
	}
	
	public static String loadText(String url, String charset){
		StringBuffer sb = new StringBuffer();
		java.io.InputStream is=null;
		AndroidHttpClient client = null;
		try {
			client = AndroidHttpClient.newInstance("xuexiban");
			// 创建 HttpGet 方法，该方法会自动处理 URL 地址的重定向
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = client.execute(httpGet);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				// 错误处理
				return null;
			}
			is = response.getEntity().getContent();
			InputStreamReader isr=new InputStreamReader(is, charset);
			char[] buf=new char[512];
			int n=-1;
			while((n=isr.read(buf))!=-1){
				sb.append(buf, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(client!=null)
				client.close();
		}
		return sb.toString();
	}
	
	private String getFileName(HttpResponse response, HttpRequestBase request){
		Header head = response.getFirstHeader("Content-Disposition");
		if(head!=null){
			String str = head.getValue();
			int pos = str.indexOf("filename=");
			return str.substring(pos+9);
		}else{
			String path = request.getURI().getPath();
			int pos = path.lastIndexOf('/');
			return pos==-1?path:path.substring(pos+1);
		}
	}
	
	void copyAndClose(InputStream is,OutputStream os){
		try {
			this.copy(is,os);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 在流之间拷贝数据
	 * @param is 输入流
	 * @param os 输出流
	 * @throws IOException 读写异常
	 */
	void copy(InputStream is,OutputStream os) throws IOException{
		byte[] buf = new byte[512];
		int count = is.read(buf); 
		while(count!=-1){ 
			os.write(buf,0,count); 
			count = is.read(buf);
		}
	}
}
